/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.iwords.api.web.alipay;

import com.alipay.client.base.PartnerConfig;
import com.alipay.client.security.RSASignature;
import com.alipay.client.util.StringUtil;
import com.iwords.api.web.base.BaseAction;
import com.iwords.constants.Constants;
import com.iwords.service.AccountServiceLocal;
import com.iwords.service.TeacherService;
import com.iwords.service.UserServiceLocal;
import com.iwords.service.object.AccountEntity;
import com.iwords.service.object.TeacherEntity;

import com.iwords.service.object.UserEntity;
import com.iwords.utils.CodeUtils;
import com.iwords.utils.StringUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author sunmellon
 */
@WebServlet(name = "IWordsAPIAlipayServlet", urlPatterns = {"/alipayTradeAPI", "/alipayNotifyAPI", "/alipayStartAPI", "/alipayDiscountAPI", "/alipayReturnAPI"})
public class IWordsAlipayServlet extends BaseAction<AccountEntity> {

    /**
     * 创建订单，并直接返回签名过的订单信息给客户端。
     */
    void alipayTrade(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, JSONException {
        response.setCharacterEncoding("utf-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        JSONObject result = new JSONObject();
        //检查商户PartnerConfig.java文件的配置参数
        if (!checkInfo()) {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode("缺少partner或者seller配置信息。"));
            return;
        }

        String orderInfo = getSignData(request);
        String sign = sign(orderInfo, PartnerConfig.RSA_PRIVATE);

        try {
            result.put(Constants.IS_SUCCESS, Boolean.TRUE);
            JSONObject defaultValue = new JSONObject().put("orderInfo", orderInfo);
            defaultValue.put("sign", sign);
            result.put(Constants.DEFAULT_VALUE, defaultValue);
        } catch (Exception e) {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            log("参数异常", e);
            result.put(Constants.MESSAGE, CodeUtils.encode("参数异常"));
        }
        jsonPrint(response, result);
    }

    //检查商户PartnerConfig.java文件的配置参数
    private boolean checkInfo() {
        String partner = PartnerConfig.PARTNER;
        String seller = PartnerConfig.SELLER;
        //如果合作商户ID为空或者账号ID为空返回false
        if (StringUtil.isBlank(partner) || StringUtil.isBlank(seller)) {
            return false;
        }

        return true;
    }

    /**
     * 准备待签名的数据
     * 
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    private String getSignData(HttpServletRequest request) throws UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");

        AccountEntity account = new AccountEntity();
        String userid = request.getParameter("userid");
        if (StringUtils.isNotBlank(userid)) {
            account.setUserid(Long.parseLong(userid));
        }
        String teacherid = request.getParameter("teacherid");
        if (StringUtils.isNotBlank(teacherid)) {
            account.setTeacherid(Long.parseLong(teacherid));
        }
        String total_fee = request.getParameter("total_fee");
        BigDecimal accountAmt = new BigDecimal(total_fee);

        account.setAccountamt(accountAmt.multiply(new BigDecimal(100)).intValue());

        account.setStatus(AccountEntity.WAIT_PAY);
        account.setCreatetime(new Date());
        account.setUpdatetime(new Date());
        accountService.create(account);
        //account.setId(10000L);


        //合作商户ID
        String partner = PartnerConfig.PARTNER;
        //卖家帐号
        String seller = PartnerConfig.SELLER;
        // 外部交易号 这里取当前时间，商户可根据自己的情况修改此参数，但保证唯一性
        String outTradeNo = account.getId().toString();
        // 商品名称
        String subject = "爱词软件和技术服务费";
        // 商品具体描述
        String body = "如果付款遇到问题，请邮件联系5iwords.com@gmail.com或电话联系15068851851.";
        // 商品总价
        String totalFee = total_fee;

        String notify_url = "http://www.5iwords.com/api/alipayNotifyAPI";

        //组装待签名数据
        String signData = "partner=" + "\"" + partner + "\"";
        signData += "&";
        signData += "seller=" + "\"" + seller + "\"";
        signData += "&";
        signData += "out_trade_no=" + "\"" + outTradeNo + "\"";
        signData += "&";
        signData += "subject=" + "\"" + subject + "\"";
        signData += "&";
        signData += "body=" + "\"" + body + "\"";
        signData += "&";
        signData += "total_fee=" + "\"" + totalFee + "\"";
        signData += "&";
        signData += "notify_url=" + "\"" + notify_url + "\"";
        return signData;
    }

    /**
     * 对参数进行签名
     * 
     * @param signData 待签名数据，key rsa商户私钥
     * @return
     */
    private String sign(String signData, String key) {
        System.out.println("signData:" + signData);
        String sign = "";
        try {
            sign = RSASignature.sign(signData, key);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return sign;
    }

    /**
     * 创建订单，返回订单号给客户端，供客户端完成支付宝支付流程
     */
    void alipayStart(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, JSONException {
        System.out.println("IWordsAlipayServlet.alipayStart()");
        AccountEntity account = new AccountEntity();
        JSONObject result = new JSONObject();
        try {
            String userid = request.getParameter("userid");
            if (StringUtils.isNotBlank(userid)) {
                account.setUserid(Long.parseLong(userid));
            }
            String teacherid = request.getParameter("teacherid");
            if (StringUtils.isNotBlank(teacherid)) {
                account.setTeacherid(Long.parseLong(teacherid));
            }
            String accountAmtStr = request.getParameter("total_fee");
            BigDecimal accountAmt = new BigDecimal(accountAmtStr);

            account.setAccountamt(accountAmt.multiply(new BigDecimal(100)).intValue());

            account.setStatus(AccountEntity.WAIT_PAY);
            account.setCreatetime(new Date());
            account.setUpdatetime(new Date());
            accountService.create(account);
            result.put(Constants.IS_SUCCESS, Boolean.TRUE);

            JSONObject defaultValue = new JSONObject().put("out_trade_id", account.getId());
            result.put(Constants.DEFAULT_VALUE, defaultValue);
        } catch (Exception e) {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            log("参数异常", e);
            result.put(Constants.MESSAGE, CodeUtils.encode("参数异常"));
        }
        jsonPrint(response, result);

    }
    @EJB
    AccountServiceLocal accountService;

    /**
     * 用户支付成功后，支付宝同步回调逻辑。
     * 以下是支付宝提供的api接口中jsp方式相应的说明：
     * 
     * 功能：支付宝页面跳转同步通知页面
     * 版本：3.2
     * 日期：2011-03-17
     * 说明：
     * 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
     * 该代码仅供学习和研究支付宝接口使用，只是提供一个参考。
     * //***********页面功能说明***********
     * 该页面可在本机电脑测试
     * 可放入HTML等美化页面的代码、商户业务逻辑程序代码
     * TRADE_FINISHED(表示交易已经成功结束，为普通即时到帐的交易状态成功标识);
     * TRADE_SUCCESS(表示交易已经成功结束，为高级即时到帐的交易状态成功标识);
     * 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException 
     */
    void alipayReturn(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, JSONException {

        System.out.println("com.iwords.api.web.alipay.IWordsAlipayServlet.alipayReturn()");
        JSONObject result = new JSONObject();
        //获取手机客户端发送回来的支付宝支付完成消息



        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//

        String trade_no = request.getParameter("trade_no");//支付宝交易号
        String order_no = request.getParameter("out_trade_no");//获取订单号
        //String total_fee = request.getParameter("total_fee");//获取总金额
        //System.out.println("trade_no = " + trade_no);
        //System.out.println("order_no = " + order_no);
        //System.out.println("total_fee = " + total_fee);

        String buyer_email = request.getParameter("buyer_email");//买家支付宝账号
        //System.out.println("buyer_email = " + buyer_email);
        //String trade_status = request.getParameter("trade_status");//交易状态

        String useridStr = request.getParameter("userid");
        Long userid = null;
        if (StringUtils.isNotBlank(useridStr)) {
            userid = Long.parseLong(useridStr);
        }




        //请在这里加上商户的业务逻辑程序代码
        //System.out.println("trade_status=" + trade_status);


        if (order_no != null) {
            //首先更新支付宝账户信息
            AccountEntity account = accountService.find(Long.valueOf(order_no));

            if (account == null) {
                //对应的订单编号不存在
                result.put(Constants.IS_SUCCESS, Boolean.FALSE);
                result.put(Constants.MESSAGE, CodeUtils.encode("支付宝支付成功，爱词授权失败：orderno:" + order_no));

            } else if (!account.getUserid().equals(userid)) {
                //对应的客户不匹配
                result.put(Constants.IS_SUCCESS, Boolean.FALSE);
                result.put(Constants.MESSAGE, CodeUtils.encode("爱词授权失败：orderno:" + order_no + " 参数异常"));
            } else {

                account.setAlipayNumber(trade_no);
                account.setAlipayEmail(buyer_email);

                if (accountService.updateAccountForAlipay(account)) {//更新AccountDetail表
                    result.put(Constants.IS_SUCCESS, Boolean.TRUE);
                    //AccountDetail表更新成功，则应该更新用户表，加入TeacherID
                    System.out.println("com.iwords.api.web.alipay.IWordsAlipayServlet.alipayReturn() account.getTeacherid() = " + account.getTeacherid());
                    UserEntity user = userService.find(account.getUserid());
                    user.setTeacherid(account.getTeacherid());
                    userService.edit(user);
                } else {
                    result.put(Constants.IS_SUCCESS, Boolean.FALSE);
                    result.put(Constants.MESSAGE, CodeUtils.encode("支付宝支付成功，爱词授权失败:order_no=" + trade_no));
                }



            }
        } else {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode("支付宝支付成功，爱词授权失败:order_no is null"));
        }
        //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
        jsonPrint(response, result);

    }
    @EJB
    TeacherService teacherService;
    @EJB
    UserServiceLocal userService;

    /**
     * 判断推广Id的正确性。
     * 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException 
     */
    void alipayDiscount(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, JSONException {
        JSONObject result = new JSONObject();

        String discountId = request.getParameter("discountId");
        if (discountId != null || discountId.length() > 0) {
            TeacherEntity teacher = new TeacherEntity();
            teacher.setMarketingid(discountId);
            teacher = teacherService.findTeacherByMarktingID(teacher);
            if (teacher != null) {

                result.put(Constants.IS_SUCCESS, Boolean.TRUE);
                JSONObject defaultValue = new JSONObject().put("teacherid", teacher.getId());
                result.put(Constants.DEFAULT_VALUE, defaultValue);
            } else {
                result.put(Constants.IS_SUCCESS, Boolean.FALSE);
                result.put(Constants.MESSAGE, CodeUtils.encode("优惠券不存在"));
            }
        } else {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode("优惠券不存在"));
        }

        jsonPrint(response, result);
    }

    /**
     * 获得验签名的数据
     * @param map
     * @return
     * @throws Exception 
     */
    @SuppressWarnings("unchecked")
    private String getVerifyData(Map map) {
        String notify_data = (String) ((Object[]) map.get("notify_data"))[0];
        return "notify_data=" + notify_data;
    }

    /**
     * 接收通知并处理
     * 
     * @author 3y
     * @version $Id: NotifyReceiver.java, v 0.1 2011-8-15 下午03:11:58 3y Exp $
     */
    void alipayNotify(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        System.out.println("********Received notify from alipay.com!");
        //获得通知参数
        Map map = request.getParameterMap();
        //获得通知签名
        String sign = (String) ((Object[]) map.get("sign"))[0];
        //获得待验签名的数据
        String verifyData = getVerifyData(map);
        boolean verified = false;
        //使用支付宝公钥验签名
        try {
            verified = RSASignature.doCheck(verifyData, sign, PartnerConfig.RSA_ALIPAY_PUBLIC);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PrintWriter out = response.getWriter();
        System.out.println("********Received notify from alipay.com! verified = " + verified);
        //验证签名通过
        if (verified) {
            //根据交易状态处理业务逻辑
            //当交易状态成功，处理业务逻辑成功。回写success
            String notify_data = request.getParameter("notify_data");
            Map<String, String> params = this.parse(notify_data);
            String out_trade_no = params.get("out_trade_no");
            String buyer_email = params.get("buyer_email");
            String trade_no = params.get("trade_no");
            String total_fee = params.get("total_fee");

            System.out.println("********Received notify from alipay.com! out_trade_no="+out_trade_no);
            System.out.println("********Received notify from alipay.com! buyer_email="+buyer_email);
            System.out.println("********Received notify from alipay.com! trade_no="+trade_no);
            System.out.println("********Received notify from alipay.com! total_fee="+total_fee);
            
            
            Long accountId = Long.valueOf(out_trade_no);
            Integer fee = (int) Double.parseDouble(total_fee) * 100;
            AccountEntity account = accountService.find(accountId);
            if (account == null) {
                System.out.println("*****api******IWordsAlipayServlet.alipayNotify() can not find the trade. out_trade_no = " + out_trade_no);
                out.println("fail");
                return;
            }
            account.setAlipayEmail(buyer_email);
            account.setAlipayNumber(trade_no);
            if (account.getAccountamt().equals(fee)) {
                if (accountService.updateAccountForAlipay(account)) {
                    System.out.println("*****api******IWordsAlipayServlet.alipayNotify() UPDATE ACCOUNT SUCCESS");
                    out.println("success");	//请不要修改或删除
                } else {
                    System.out.println("*****api******IWordsAlipayServlet.alipayNotify() UPDATE ACCOUNT FAIL");
                    out.println("fail");
                }
            } else {
                System.out.println("*****api******IWordsAlipayServlet.alipayNotify() need fee:" + fee + " payed fee: " + total_fee);
                out.println("fail");
            }
            System.out.println("c*****api******IWordsAlipayServlet.alipayNotify() account.getTeacherid() = " + account.getTeacherid());
            account = accountService.find(account.getId());//根据Account id 获取account信息
            UserEntity user = userService.find(account.getUserid());
            user.setTeacherid(account.getTeacherid());
            userService.edit(user);
            out.print("success");
        } else {
            System.out.println("Received notify from alipay.com! verify failed.");
            out.print("fail");
        }


//        System.out.println("*****api******IWordsAlipayServlet.alipayNotify()");
//
//        Map<String, String> params = new HashMap<String, String>();
//        Map requestParams = request.getParameterMap();
//        System.out.println("*****api******IWordsAlipayServlet.alipayNotify() requestParams=" + requestParams);
//        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
//            String name = (String) iter.next();
//            System.out.println("*****api******IWordsAlipayServlet.alipayNotify() name = " + name);
//            String[] values = (String[]) requestParams.get(name);
//            System.out.println("*****api******IWordsAlipayServlet.alipayNotify() values.length = " + values.length);
//            String valueStr = "";
//            for (int i = 0; i < values.length; i++) {
//                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
//            }
//            System.out.println("*****api******IWordsAlipayServlet.alipayNotify() valueStr = " + valueStr);
//            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
//            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
//            params.put(name, valueStr);
//        }
//


        /*
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        
        String trade_no = request.getParameter("trade_no");				//支付宝交易号
        String order_no = request.getParameter("out_trade_no");	        //获取订单号
        String total_fee = request.getParameter("total_fee");	        //获取总金额
        //String subject = new String(request.getParameter("subject").getBytes("ISO-8859-1"), "utf-8");//商品名称、订单名称
        //String body = "";
        //if (request.getParameter("body") != null) {
        //    body = new String(request.getParameter("body").getBytes("ISO-8859-1"), "utf-8");//商品描述、订单备注、描述
        //}
        String buyer_email = request.getParameter("buyer_email");		//买家支付宝账号
        String trade_status = request.getParameter("trade_status");		//交易状态
        
        System.out.println("*****api******IWordsAlipayServlet.alipayNotify() trade_no=" + trade_no);
        System.out.println("*****api******IWordsAlipayServlet.alipayNotify() order_no=" + order_no);
        System.out.println("*****api******IWordsAlipayServlet.alipayNotify() total_fee=" + total_fee);
        System.out.println("*****api******IWordsAlipayServlet.alipayNotify() buyer_email=" + buyer_email);
        System.out.println("*****api******IWordsAlipayServlet.alipayNotify() trade_status=" + trade_status);
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        
        
        //PrintWriter out = response.getWriter();
        try {
        if (AlipayNotify.verify(params)) {//验证成功
        System.out.println("*****api******IWordsAlipayServlet.alipayNotify() valid success");
        //////////////////////////////////////////////////////////////////////////////////////////
        //请在这里加上商户的业务逻辑程序代码
        
        //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
        
        if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
        System.out.println("*****api******IWordsAlipayServlet.alipayNotify() TRADESUCCESS");
        //判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
        //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
        //如果有做过处理，不执行商户的业务程序
        AccountEntity account = new AccountEntity();
        account.setId(Long.valueOf(order_no));
        account.setAlipayEmail(buyer_email);
        account.setAlipayNumber(trade_no);
        if (accountService.updateAccountForAlipay(account)) {
        System.out.println("*****api******IWordsAlipayServlet.alipayNotify() UPDATE ACCOUNT SUCCESS");
        out.println("success");	//请不要修改或删除
        } else {
        System.out.println("*****api******IWordsAlipayServlet.alipayNotify() UPDATE ACCOUNT FAIL");
        out.println("fail");
        }
        System.out.println("c*****api******IWordsAlipayServlet.alipayNotify() account.getTeacherid() = " + account.getTeacherid());
        account = accountService.find(account.getId());//根据Account id 获取account信息
        UserEntity user = userService.find(account.getUserid());
        user.setTeacherid(account.getTeacherid());
        userService.edit(user);
        } else {
        System.out.println("*****api******IWordsAlipayServlet.alipayNotify() TRADE FAIL");
        //参数错误
        out.println("fail");	//请不要修改或删除
        }
        
        //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
        
        } else {//验证失败
        System.out.println("*****api******IWordsAlipayServlet.alipayNotify() valid fail");
        out.println("fail");
        }
        } catch (Exception e) {
        System.out.println("*****api******IWordsAlipayServlet.alipayNotify() Catch Exception e.getMessage() = " + e.getMessage());
        e.printStackTrace();
        out.println("fail");
        } finally {
        out.close();
        }
         * *
         */
    }

    @Override
    public AccountEntity initEntity(HttpServletRequest req) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, JSONException {
        System.out.println("*****api******IWordsAlipayServlet.doProcess() request.getPathInfo() = " + request.getPathInfo());
        System.out.println("*****api******IWordsAlipayServlet.doProcess() request.getServletPath() = " + request.getServletPath());
        String servletPath = request.getServletPath();
        System.out.println("com.iwords.api.web.alipay.IWordsAlipayServlet.doProcess() processRequest(request, response) servletPath = " + servletPath);
        if ("/alipayStartAPI".equals(servletPath)) {
            System.out.println("*****api******alipayStart(request, response);");
            alipayStart(request, response);
        } else if ("/alipayTradeAPI".equals(servletPath)) {
            System.out.println("*****api******alipayTrade(request, response);");
            alipayTrade(request, response);
        } else if ("/alipayDiscountAPI".equals(servletPath)) {
            System.out.println("*****api******alipayDiscount(request, response);");
            alipayDiscount(request, response);
        } else if ("/alipayReturnAPI".equals(servletPath)) {
            System.out.println("*****api******alipayReturn(request, response);");
            alipayReturn(request, response);
        } else if ("/alipayNotifyAPI".equals(servletPath)) {
            System.out.println("*****api******alipayNotify(request, response);");
            alipayNotify(request, response);
        } else if ("/apiAlipayNotify".equals(servletPath)) {
            System.out.println("*****api******alipayNotify(request, response);");
            alipayNotify(request, response);
        } else {
            System.out.println("*****api******non(request, response); servletPath = " + servletPath);
        }
    }

    public static void main(String args[]) {
    }

    public Map<String, String> parse(String xml) {
//        String xml = "<notify>"
//                + "<partner>2088602310398815</partner>"
//                + "<discount>0.00</discount>"
//                + "<payment_type>1</payment_type>"
//                + "<subject>123456</subject>"
//                + "<trade_no>2011111525445944</trade_no>"
//                + "<buyer_email>yunzi@taobao.com</buyer_email>"
//                + "<gmt_create>2011-11-15 14:39:16</gmt_create>"
//                + "<quantity>1</quantity>"
//                + "<out_trade_no>111514390811773</out_trade_no>"
//                + "<seller_id>2088602310398815</seller_id>"
//                + "<trade_status>TRADE_FINISHED</trade_status>"
//                + "<is_total_fee_adjust>N</is_total_fee_adjust>"
//                + "<total_fee>0.01</total_fee>"
//                + "<gmt_payment>2011-11-15 14:39:16</gmt_payment>"
//                + "<seller_email>5iwords.com@gmail.com</seller_email>"
//                + "<gmt_close>2011-11-15 14:39:16</gmt_close>"
//                + "<price>0.01</price>"
//                + "<buyer_id>2088202305898443</buyer_id>"
//                + "<use_coupon>N</use_coupon>"
//                + "</notify>";
        Map<String, String> params = new HashMap<String, String>();
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(new StringReader(xml));
            Element root = document.getRootElement();
            for (Iterator iter = root.elementIterator(); iter.hasNext();) {
                Element element = (Element) iter.next();
                String name = element.getName();
                String value = element.getStringValue();
                //System.out.println(name+":"+value);
                params.put(name, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return params;
    }
}
